package com.phonetools.commonutils.android.phone

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.telephony.TelephonyManager
import com.phonetools.commonutils.android.getTelephonyManager
import java.util.*

/**
 * 调用拨号界面
 * @param context\
 * @param phone 电话号码
 */
fun call(context: Context, phone: String) {
    val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phone"))
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    context.startActivity(intent)
}

/**
 * 直接调用短信接口发短信
 * @param phoneNumber 对方手机号码
 * @param message 要发送的信息
 * @param sentPI 发送监听
 * @param deliverPI 送达监听
 */
fun sendSMS(phoneNumber: String, message: String, sentPI: PendingIntent, deliverPI: PendingIntent) {
    // 获取短信管理器
    val smsManager = android.telephony.SmsManager.getDefault()
    if (message.length > 70) {
        // 拆分短信内容（手机短信长度限制）
        val divideContents = smsManager.divideMessage(message)
        val sentIntents: ArrayList<PendingIntent> = arrayListOf()
        val deliverIntents: ArrayList<PendingIntent> = arrayListOf()
        for (text in divideContents) {
            sentIntents.add(sentPI)
            deliverIntents.add(deliverPI)
        }
        smsManager.sendMultipartTextMessage(
            phoneNumber,
            null,
            divideContents,
            sentIntents,
            deliverIntents
        )
    } else {
        smsManager.sendTextMessage(phoneNumber, null, message, sentPI, deliverPI)
    }
}

/**
 * 是否已插入sim卡且已接入
 * @return Boolean
 */
fun isSimReady(context: Context): Boolean {
    val telMgr = getTelephonyManager(context)
    return when (telMgr.simState) {
        TelephonyManager.SIM_STATE_READY -> {
            true
        }
        else -> {
            false
        }
    }
}